import functools
class Solution(object):
    def countPyramids(self, grid):
        m = len(grid)
        n = len(grid[0])
        ans = 0
        @functools.cache
        def dfs1(i, j):
            if 0 <= i < m and 0 <= j < n:
                if grid[i][j] == 1:
                    if dfs1(i + 1, j) > 0:
                        return 1 + min(dfs1(i + 1 , j - 1), dfs1(i + 1, j + 1))
                    else:
                        return 1
                else:
                    return 0    
            else:
                return 0
        @functools.cache
        def dfs2(i, j):
            if 0 <= i < m and 0 <= j < n:
                if grid[i][j] == 1:
                    if dfs2(i - 1, j) > 0:
                        return 1 + min(dfs2(i - 1 , j - 1), dfs2(i - 1, j + 1))
                    else:
                        return 1
                else:
                    return 0    
            else:
                return 0
        for i in range(m):
            for j in range(n):
                ans += max(0, dfs1(i, j) - 1) + max(0, dfs2(i, j) - 1) 
        return ans

data = Solution()
grid = [[1,1,1,1,0],[1,1,1,1,1],[1,1,1,1,1],[0,1,0,0,1]]
print(data.countPyramids(grid))